import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import sys

# 添加项目根目录到系统路径
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../../')))

from config.config import DATA_CONFIG, VISUALIZATION_CONFIG

class WeatherVisualizer:
    """
    天气数据可视化类，负责生成各种图表
    """
    def __init__(self):
        self.processed_data_path = os.path.join(os.path.dirname(__file__), '../../', DATA_CONFIG['processed_data_path'])
        self.save_path = os.path.join(os.path.dirname(__file__), '../../', VISUALIZATION_CONFIG['save_path'])
        self.figsize = VISUALIZATION_CONFIG['default_figsize']
        self.style = VISUALIZATION_CONFIG['style']
        
        # 设置matplotlib样式
        plt.style.use(self.style)
        
        # 确保图表保存目录存在
        os.makedirs(self.save_path, exist_ok=True)
    
    def load_data(self, data_type):
        """
        加载处理后的数据
        data_type: 'current', 'forecast', 'historical', 或 'all'
        """
        file_map = {
            'current': 'current_weather.csv',
            'forecast': 'weather_forecast.csv',
            'historical': 'historical_weather.csv',
            'all': 'all_weather_data.csv'
        }
        
        if data_type not in file_map:
            print(f"未知的数据类型: {data_type}")
            return None
        
        file_path = os.path.join(self.processed_data_path, file_map[data_type])
        if not os.path.exists(file_path):
            print(f"文件不存在: {file_path}")
            return None
        
        try:
            df = pd.read_csv(file_path)
            
            # 转换时间列
            time_cols = ['timestamp', 'forecast_time']
            for col in time_cols:
                if col in df.columns:
                    df[col] = pd.to_datetime(df[col])
            
            return df
        except Exception as e:
            print(f"加载数据失败: {e}")
            return None
    
    def plot_temperature_trends(self, data_type='forecast', city=None, save=True):
        """
        绘制温度趋势图
        """
        df = self.load_data(data_type)
        if df is None or df.empty:
            return None
        
        # 确定时间列
        time_col = 'forecast_time' if 'forecast_time' in df.columns else 'timestamp'
        if time_col not in df.columns:
            print(f"数据中缺少时间列")
            return None
        
        # 筛选城市数